<template>
  <div class="symptom-assessment">
    <!-- 页面头部 -->
    <div class="assessment-header">
      <h1 class="title">
        <el-icon><DocumentChecked /></el-icon>
        症状自评系统
      </h1>
      <p class="subtitle">请详细描述您的症状，AI将为您提供专业的初步分析</p>
    </div>

    <!-- 评估表单 -->
    <el-card class="assessment-form" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>症状信息录入</span>
          <el-button type="primary" @click="quickAnalyze" :disabled="!form.mainSymptoms">
            快速分析
          </el-button>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <!-- 基本信息 -->
        <div class="form-section">
          <h3 class="section-title">基本信息</h3>
          
          <el-form-item label="评估标题" prop="title">
            <el-input 
              v-model="form.title" 
              placeholder="请输入评估标题，如：头痛症状评估"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="主要症状" prop="mainSymptoms">
            <el-input 
              v-model="form.mainSymptoms" 
              type="textarea" 
              :rows="4"
              placeholder="请详细描述您的主要症状，包括症状的具体表现、位置等"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="持续时间" prop="duration">
            <el-select v-model="form.duration" placeholder="请选择症状持续时间">
              <el-option label="几分钟" value="几分钟" />
              <el-option label="几小时" value="几小时" />
              <el-option label="1-2天" value="1-2天" />
              <el-option label="3-7天" value="3-7天" />
              <el-option label="1-2周" value="1-2周" />
              <el-option label="1个月以上" value="1个月以上" />
              <el-option label="间歇性出现" value="间歇性出现" />
            </el-select>
          </el-form-item>

          <el-form-item label="疼痛等级">
            <div class="pain-level">
              <el-slider 
                v-model="form.painLevel" 
                :min="0" 
                :max="10" 
                :step="1"
                show-stops
                show-input
              />
              <div class="pain-desc">
                <span class="pain-label">无痛</span>
                <span class="pain-label">轻微</span>
                <span class="pain-label">中等</span>
                <span class="pain-label">严重</span>
                <span class="pain-label">剧烈</span>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- 详细信息 -->
        <div class="form-section">
          <h3 class="section-title">详细信息</h3>
          
          <el-form-item label="伴随症状">
            <el-checkbox-group v-model="accompanyingSymptomsList">
              <el-checkbox label="发热" />
              <el-checkbox label="恶心" />
              <el-checkbox label="呕吐" />
              <el-checkbox label="头晕" />
              <el-checkbox label="乏力" />
              <el-checkbox label="食欲不振" />
              <el-checkbox label="失眠" />
              <el-checkbox label="心悸" />
              <el-checkbox label="呼吸困难" />
              <el-checkbox label="其他" />
            </el-checkbox-group>
            <el-input 
              v-if="accompanyingSymptomsList.includes('其他')"
              v-model="otherSymptoms"
              placeholder="请描述其他伴随症状"
              class="mt-2"
            />
          </el-form-item>

          <el-form-item label="诱发因素">
            <el-input 
              v-model="form.triggerFactors" 
              type="textarea" 
              :rows="3"
              placeholder="请描述可能的诱发因素，如运动、饮食、情绪变化等"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="缓解因素">
            <el-input 
              v-model="form.reliefFactors" 
              type="textarea" 
              :rows="3"
              placeholder="请描述能够缓解症状的因素，如休息、药物、特定姿势等"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="既往类似症状">
            <el-input 
              v-model="form.previousEpisodes" 
              type="textarea" 
              :rows="3"
              placeholder="请描述是否曾经出现过类似症状，以及当时的处理情况"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="当前用药">
            <el-input 
              v-model="form.currentMedications" 
              type="textarea" 
              :rows="3"
              placeholder="请列出当前正在服用的药物，包括处方药和非处方药"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitAssessment" :loading="submitting">
            提交评估
          </el-button>
        </div>
      </el-form>
    </el-card>

    <!-- AI分析结果 -->
    <el-card v-if="analysisResult" class="analysis-result">
      <template #header>
        <div class="card-header">
          <span>AI分析结果</span>
          <el-tag :type="getRiskLevelType(analysisResult.riskLevel)">
            {{ getRiskLevelText(analysisResult.riskLevel) }}
          </el-tag>
        </div>
      </template>

      <div class="analysis-content">
        <div class="analysis-item">
          <h4><el-icon><Document /></el-icon> AI分析报告</h4>
          <p class="analysis-text">{{ analysisResult.analysis }}</p>
        </div>

        <div class="analysis-item">
          <h4><el-icon><OfficeBuilding /></el-icon> 推荐科室</h4>
          <el-tag size="large" type="info">{{ analysisResult.recommendedDepartment }}</el-tag>
        </div>

        <div class="analysis-item">
          <h4><el-icon><Warning /></el-icon> 风险提示</h4>
          <el-alert 
            :title="getRiskAlertTitle(analysisResult.riskLevel)"
            :type="getRiskAlertType(analysisResult.riskLevel)"
            :description="getRiskAlertDesc(analysisResult.riskLevel)"
            show-icon
            :closable="false"
          />
        </div>

        <div class="analysis-actions">
          <el-button type="primary" @click="goToAppointment">
            立即预约
          </el-button>
          <el-button @click="saveAssessment" :loading="saving">
            保存评估
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 历史评估 -->
    <el-card class="history-assessments">
      <template #header>
        <div class="card-header">
          <span>历史评估记录</span>
          <el-button text @click="loadHistory">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-table :data="historyList" v-loading="historyLoading">
        <el-table-column prop="title" label="评估标题" />
        <el-table-column prop="mainSymptoms" label="主要症状" show-overflow-tooltip />
        <el-table-column prop="riskLevel" label="风险等级">
          <template #default="{ row }">
            <el-tag :type="getRiskLevelType(row.riskLevel)">
              {{ getRiskLevelText(row.riskLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recommendedDepartment" label="推荐科室" />
        <el-table-column prop="createdAt" label="评估时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button text @click="viewDetail(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination" v-if="historyTotal > 0">
        <el-pagination
          v-model:current-page="historyPage"
          v-model:page-size="historyPageSize"
          :total="historyTotal"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadHistory"
          @size-change="loadHistory"
        />
      </div>
    </el-card>

    <!-- 评估详情对话框 -->
    <el-dialog v-model="detailVisible" title="评估详情" width="60%">
      <div v-if="selectedAssessment" class="assessment-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="评估标题">{{ selectedAssessment.title }}</el-descriptions-item>
          <el-descriptions-item label="评估时间">{{ formatDate(selectedAssessment.createdAt) }}</el-descriptions-item>
          <el-descriptions-item label="主要症状" :span="2">{{ selectedAssessment.mainSymptoms }}</el-descriptions-item>
          <el-descriptions-item label="持续时间">{{ selectedAssessment.duration }}</el-descriptions-item>
          <el-descriptions-item label="疼痛等级">{{ selectedAssessment.painLevel }}/10</el-descriptions-item>
          <el-descriptions-item label="风险等级">
            <el-tag :type="getRiskLevelType(selectedAssessment.riskLevel)">
              {{ getRiskLevelText(selectedAssessment.riskLevel) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="推荐科室">{{ selectedAssessment.recommendedDepartment }}</el-descriptions-item>
          <el-descriptions-item label="AI分析" :span="2">
            <div class="ai-analysis">{{ selectedAssessment.aiAnalysis }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DocumentChecked, Document, OfficeBuilding, Warning, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const saving = ref(false)
const historyLoading = ref(false)
const detailVisible = ref(false)

// 表单数据
const form = reactive({
  title: '',
  mainSymptoms: '',
  duration: '',
  painLevel: 0,
  triggerFactors: '',
  reliefFactors: '',
  previousEpisodes: '',
  currentMedications: ''
})

// 伴随症状
const accompanyingSymptomsList = ref([])
const otherSymptoms = ref('')

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入评估标题', trigger: 'blur' }
  ],
  mainSymptoms: [
    { required: true, message: '请描述主要症状', trigger: 'blur' },
    { min: 10, message: '症状描述至少10个字符', trigger: 'blur' }
  ]
}

// AI分析结果
const analysisResult = ref(null)

// 历史记录
const historyList = ref([])
const historyPage = ref(1)
const historyPageSize = ref(10)
const historyTotal = ref(0)
const selectedAssessment = ref(null)

const formRef = ref()

// 计算属性
const accompanyingSymptoms = computed(() => {
  let symptoms = accompanyingSymptomsList.value.filter(s => s !== '其他').join(', ')
  if (accompanyingSymptomsList.value.includes('其他') && otherSymptoms.value) {
    symptoms += symptoms ? ', ' + otherSymptoms.value : otherSymptoms.value
  }
  return symptoms
})

// 方法
const quickAnalyze = async () => {
  if (!form.mainSymptoms) {
    ElMessage.warning('请先描述主要症状')
    return
  }

  loading.value = true
  try {
    const requestData = {
      ...form,
      accompanyingSymptoms: accompanyingSymptoms.value
    }

    const response = await axios.post('/api/symptom/analyze', requestData)
    
    if (response.data.success) {
      analysisResult.value = response.data.data
      ElMessage.success('AI分析完成')
    } else {
      ElMessage.error(response.data.message || 'AI分析失败')
    }
  } catch (error) {
    console.error('AI分析失败:', error)
    ElMessage.error('AI分析失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const submitAssessment = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  submitting.value = true
  try {
    const requestData = {
      ...form,
      accompanyingSymptoms: accompanyingSymptoms.value
    }

    const response = await axios.post('/api/symptom/assessment', requestData, {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
    
    if (response.data.success) {
      analysisResult.value = response.data.data
      ElMessage.success('症状评估提交成功')
      loadHistory() // 刷新历史记录
    } else {
      ElMessage.error(response.data.message || '提交失败')
    }
  } catch (error) {
    console.error('提交评估失败:', error)
    ElMessage.error('提交失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

const saveAssessment = async () => {
  if (!analysisResult.value) {
    ElMessage.warning('请先进行症状分析')
    return
  }

  saving.value = true
  try {
    const requestData = {
      ...form,
      accompanyingSymptoms: accompanyingSymptoms.value,
      aiAnalysis: analysisResult.value.analysis,
      riskLevel: analysisResult.value.riskLevel,
      recommendedDepartment: analysisResult.value.recommendedDepartment
    }

    const response = await axios.post('/api/symptom/assessment', requestData, {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
    
    if (response.data.success) {
      ElMessage.success('评估保存成功')
      loadHistory() // 刷新历史记录
    } else {
      ElMessage.error(response.data.message || '保存失败')
    }
  } catch (error) {
    console.error('保存评估失败:', error)
    ElMessage.error('保存失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  formRef.value.resetFields()
  accompanyingSymptomsList.value = []
  otherSymptoms.value = ''
  analysisResult.value = null
}

const loadHistory = async () => {
  historyLoading.value = true
  try {
    const response = await axios.get('/api/symptom/assessments', {
      params: {
        pageNum: historyPage.value,
        pageSize: historyPageSize.value
      },
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      }
    })
    
    console.log('API响应:', response.data)
    
    if (response.data.success) {
      historyList.value = response.data.data.records
      historyTotal.value = response.data.data.total
    } else {
      console.error('API返回错误:', response.data.message)
      ElMessage.error(response.data.message || '获取历史记录失败')
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
    console.error('错误详情:', error.response?.data)
    ElMessage.error('加载历史记录失败: ' + (error.response?.data?.message || error.message))
  } finally {
    historyLoading.value = false
  }
}

const viewDetail = (assessment) => {
  selectedAssessment.value = assessment
  detailVisible.value = true
}

const goToAppointment = () => {
  router.push('/appointment')
}

// 工具方法
const getRiskLevelType = (level) => {
  const types = {
    'LOW': 'success',
    'MEDIUM': 'warning', 
    'HIGH': 'danger',
    'URGENT': 'danger'
  }
  return types[level] || 'info'
}

const getRiskLevelText = (level) => {
  const texts = {
    'LOW': '低风险',
    'MEDIUM': '中风险',
    'HIGH': '高风险', 
    'URGENT': '紧急'
  }
  return texts[level] || '未知'
}

const getRiskAlertType = (level) => {
  const types = {
    'LOW': 'success',
    'MEDIUM': 'warning',
    'HIGH': 'error',
    'URGENT': 'error'
  }
  return types[level] || 'info'
}

const getRiskAlertTitle = (level) => {
  const titles = {
    'LOW': '症状较轻，建议观察',
    'MEDIUM': '症状需要关注，建议就医',
    'HIGH': '症状较重，建议尽快就医',
    'URGENT': '症状紧急，请立即就医'
  }
  return titles[level] || '请关注症状变化'
}

const getRiskAlertDesc = (level) => {
  const descs = {
    'LOW': '您的症状风险较低，建议继续观察。如症状加重请及时就医。',
    'MEDIUM': '您的症状需要医生进一步评估，建议在1-2天内就医。',
    'HIGH': '您的症状风险较高，建议尽快到医院就诊，不要延误。',
    'URGENT': '您的症状可能存在紧急情况，请立即前往医院急诊科就诊。'
  }
  return descs[level] || '请根据症状严重程度决定是否就医。'
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadHistory()
})
</script>

<style scoped>
.symptom-assessment {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.assessment-header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 28px;
  color: #2c3e50;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.subtitle {
  color: #7f8c8d;
  font-size: 16px;
}

.assessment-form {
  margin-bottom: 30px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.form-section {
  margin-bottom: 30px;
}

.section-title {
  color: #2c3e50;
  border-bottom: 2px solid #3498db;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.pain-level {
  width: 100%;
}

.pain-desc {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  font-size: 12px;
  color: #7f8c8d;
}

.form-actions {
  text-align: center;
  margin-top: 30px;
}

.analysis-result {
  margin-bottom: 30px;
}

.analysis-content {
  padding: 20px 0;
}

.analysis-item {
  margin-bottom: 25px;
}

.analysis-item h4 {
  color: #2c3e50;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.analysis-text {
  line-height: 1.6;
  color: #34495e;
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #3498db;
}

.analysis-actions {
  text-align: center;
  margin-top: 20px;
}

.history-assessments {
  margin-bottom: 30px;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.assessment-detail {
  padding: 20px 0;
}

.ai-analysis {
  line-height: 1.6;
  color: #34495e;
}

.mt-2 {
  margin-top: 8px;
}

@media (max-width: 768px) {
  .symptom-assessment {
    padding: 10px;
  }
  
  .title {
    font-size: 24px;
  }
  
  .form-section {
    margin-bottom: 20px;
  }
}
</style>